using Microsoft.AspNetCore.Mvc;
using RiceShop.Models;
using RiceShop.Services;

namespace RiceShop.Controllers
{
    /// <summary>
    /// 商品控制器：处理商品相关的 HTTP 请求
    /// </summary>
    [Route("api/[controller]")]
    [ApiController]
    public class GoodController : ControllerBase
    {
        // 商品服务接口的私有字段
        private readonly IGoodService _goodService;

        /// <summary>
        /// 构造函数：通过依赖注入注入商品服务
        /// </summary>
        /// <param name="goodService">商品服务接口</param>
        public GoodController(IGoodService goodService)
        {
            _goodService = goodService;
        }

        /// <summary>
        /// 获取商品列表
        /// </summary>
        /// <param name="pageSize">每页显示的商品数量，默认为10</param>
        /// <param name="pageIndex">当前页码，默认为第1页</param>
        /// <param name="categoryId">商品分类ID，可选参数</param>
        /// <param name="keyword">搜索关键词，可选参数</param>
        /// <returns>返回分页后的商品列表和总数量</returns>
        [HttpGet("list")]
        public async Task<IActionResult> GetGoods(
            [FromQuery] int pageSize = 10,
            [FromQuery] int pageIndex = 1,
            [FromQuery] long? categoryId = null,
            [FromQuery] string? keyword = null)
        {
            var (items, total) = await _goodService.GetGoodsAsync(pageSize, pageIndex, categoryId, keyword);
            return Ok(ApiResponse<IEnumerable<Good>>.Ok(items, "获取商品列表成功", total));
        }

        /// <summary>
        /// 获取商品详情
        /// </summary>
        /// <param name="spuId">商品SPU ID</param>
        /// <returns>返回商品详细信息，如果未找到则返回404</returns>
        [HttpGet("detail/{spuId}")]
        public async Task<IActionResult> GetGoodDetail(long spuId)
        {
            var detail = await _goodService.GetGoodDetailAsync(spuId);
            if (detail == null)
                return NotFound(ApiResponse<object>.Error("商品不存在"));
            return Ok(ApiResponse<Good>.Ok(detail, "获取商品详情成功"));
        }

        /// <summary>
        /// 获取所有商品分类
        /// </summary>
        /// <returns>返回商品分类列表</returns>
        [HttpGet("categories/list")]
        public async Task<IActionResult> GetGoodCategories()
        {
            var categories = await _goodService.GetCategoriesAsync();
            return Ok(categories);
        }

        /// <summary>
        /// 获取商品评论列表
        /// </summary>
        /// <param name="spuId">商品SPU ID</param>
        /// <param name="pageSize">每页显示的评论数量，默认为10</param>
        /// <param name="pageIndex">当前页码，默认为第1页</param>
        /// <returns>返回分页后的商品评论列表和总数量</returns>
        [HttpGet("{spuId}/comments")]
        public async Task<IActionResult> GetGoodComments(
            long spuId,
            [FromQuery] int pageSize = 10,
            [FromQuery] int pageIndex = 1)
        {
            var (items, total) = await _goodService.GetGoodCommentsAsync(spuId, pageSize, pageIndex);
            
            return Ok(new
            {
                Items = items,  // 现在 items 是 List<Comment> 类型
                Total = total,
                PageSize = pageSize,
                PageIndex = pageIndex
            });
        }

        /// <summary>
        /// 创建新商品
        /// </summary>
        /// <param name="good">商品信息</param>
        /// <returns>创建的商品信息</returns>
        [HttpPost("create")]
        public async Task<IActionResult> CreateGood([FromBody] Good good)
        {
            if (!ModelState.IsValid)
            {
                return BadRequest(ApiResponse<object>.Error("请求数据无效"));
            }

            try
            {
                // 设置初始值
                good.CreateTime = DateTime.Now;
                good.UpdateTime = DateTime.Now;
                good.IsDeleted = false;
                good.Status = 1; // 假设1为正常状态
                
                // 确保价格和库存为有效值
                if (!good.SalePrice.HasValue)
                {
                    return BadRequest(ApiResponse<object>.Error("商品价格不能为空"));
                }
                
                if (!good.SpuStockQuantity.HasValue)
                {
                    good.SpuStockQuantity = 0;
                }

                var createdGood = await _goodService.CreateGoodAsync(good);
                return CreatedAtAction(
                    nameof(GetGoodDetail),
                    new { spuId = createdGood.SpuId },
                    ApiResponse<Good>.Ok(createdGood, "创建商品成功")
                );
            }
            catch (Exception ex)
            {
                return StatusCode(500, ApiResponse<object>.Error($"创建商品失败: {ex.Message}"));
            }
        }

        /// <summary>
        /// 更新商品信息
        /// </summary>
        /// <param name="spuId">商品ID</param>
        /// <param name="good">更新后的商品信息</param>
        /// <returns>操作结果</returns>
        [HttpPut("update/{spuId}")]
        public async Task<IActionResult> UpdateGood(long spuId, [FromBody] Good good)
        {
            if (!ModelState.IsValid)
            {
                return BadRequest(ApiResponse<object>.Error("请求数据无效"));
            }

            try
            {
                // 更新时间
                good.UpdateTime = DateTime.Now;
                
                // 验证价格
                if (!good.SalePrice.HasValue)
                {
                    return BadRequest(ApiResponse<object>.Error("商品价格不能为空"));
                }

                // 确保库存为有效值
                if (!good.SpuStockQuantity.HasValue)
                {
                    good.SpuStockQuantity = 0;
                }

                var updatedGood = await _goodService.UpdateGoodAsync(spuId, good);
                return Ok(ApiResponse<Good>.Ok(updatedGood, "更新商品成功"));
            }
            catch (ArgumentException ex)
            {
                return NotFound(ApiResponse<object>.Error(ex.Message));
            }
            catch (Exception ex)
            {
                return StatusCode(500, ApiResponse<object>.Error($"更新商品失败: {ex.Message}"));
            }
        }

        // /// <summary>
        // /// 更新商品详细信息
        // /// </summary>
        // /// <param name="spuId">商品SPU ID</param>
        // /// <param name="detail">更新的商品详细信息</param>
        // /// <returns>操作结果</returns>
        // [HttpPut("detail/update/{spuId}")]
        // public async Task<IActionResult> UpdateGoodDetail(long spuId, [FromBody] GoodDetail detail)
        // {
        //     if (!ModelState.IsValid)
        //     {
        //         return BadRequest(ModelState);
        //     }

        //     try
        //     {
        //         var updatedDetail = await _goodService.UpdateGoodDetailAsync(spuId, detail);
        //         return Ok(ApiResponse<GoodDetail>.Ok(updatedDetail, "更新商品详情成功"));
        //     }
        //     catch (ArgumentException ex)
        //     {
        //         return NotFound(ApiResponse<GoodDetail>.Error(ex.Message));
        //     }
        //     catch (InvalidOperationException ex)
        //     {
        //         return BadRequest(ApiResponse<GoodDetail>.Error(ex.Message));
        //     }
        //     catch (Exception)
        //     {
        //         return StatusCode(500, ApiResponse<GoodDetail>.Error("更新商品详情时发生错误"));
        //     }
        // }

        /// <summary>
        /// 删除商品
        /// </summary>
        /// <param name="spuId">商品ID</param>
        /// <returns>操作结果</returns>
        [HttpDelete("delete/{spuId}")]
        public async Task<IActionResult> DeleteGood(long spuId)
        {
            var result = await _goodService.DeleteGoodAsync(spuId);
            if (!result)
            {
                return NotFound(ApiResponse<Good>.Error("商品不存在"));
            }
            return Ok(ApiResponse<Good>.Ok(null, "删除商品成功"));
        }
    }
}